<?php

require_once 'smarty/Smarty.class.php';
require_once 'model.class.php';

class Controller{
	
	protected $models_dir = "models/";
	protected $name = "SREMCICA";
	
	public $models = array("Admin", "Translate");
	
	public $title_delimiter = "&gt;";
	
	public $data;
	
	public $dispatcher;
	
	public $languages = array();

	public $secure = false;
	
	function __construct(){
		
		// dispatched data
		global $_dispatcher;
		$this->dispatcher = $_dispatcher;
		
		// start session
		if(!session_id()) {
			session_start();
		}
		
		// view parser
		$this->template_parser = new Smarty();
		$this->template_parser->config_dir = "config";
		$this->template_parser->template_dir = "views";
		$this->template_parser->compile_dir = "tmp/templates_c";
		$this->template_parser->config_load("main.cfg");
		$lang = $this->session_get("language"); $lang = $lang ? $lang : "sr";
		$this->template_parser->config_load("language/$lang.lang");
		
		// languages
		$this->languages = explode(",",$this->template_parser->get_config_vars("languages"));
		$this->languages_long = explode(",",$this->template_parser->get_config_vars("languages_long"));
		
		// DB models
		$default_model = strtolower($this->current_controller());
		if (file_exists("$this->models_dir/$default_model.model.php")) {
			if (is_array($this->models)) {
				$this->models[] = strtotitle($default_model);
			}else{
				$this->models = Array(strtotitle($default_model));
			}
			
		}
		if ($this->models && is_array($this->models)){
			$this->models = array_unique(array_merge($this->models,array("Admin", "Translate")));
			foreach ($this->models as $model){
				require_once $this->models_dir."/".strtolower($model).".model.php";
				
				$classname = $model."Model";
				$this->{$model} = new $classname;
				$this->{$model}->_controller = $this;
				if($this->{$model}->status["code"]){
					$this->assign("error",$this->{$model}->status);
					$this->display("errors/db.error.html",false);
					die();
				}
			}
		}
		
		// secure page
		$current_method = $this->current_method();
		if($this->secure) {
			if ( !$this->_isUserLoggedIn() && !preg_match('/^login|logout$/i',$current_method) ) {
				switch ($current_method) {
					default:
						if(!$_SERVER["HTTP_REFERER"]) {
							$this->session_set("login_message","");
						}
						$this->assign("message",$this->session_get("login_message"));
						$this->assign("LOGIN",true);
						$this->display("admin/login.html");
						die();
						break;
				}
			}
		}
		
		// menu
		$menu = parse_ini_file($this->template_parser->config_dir."/menu.cfg",TRUE);
		$ctrl = strtolower($this->dispatcher["CONTROLLER"]);
		if (isset($menu[$ctrl])) {
			$menu[$ctrl]["active"] = 1;
		}
		foreach($menu as $ctrl=>&$m) {
			$cfg = $this->template_parser->get_config_vars($m["label"]);
			$m["label"] = $cfg ? $cfg : $m["label"];
		}
		$this->assign("menu",$menu);
		
		// get,post data
		$this->data = getFromInput("data");
	}
	
	function current_controller() {
		return $this->dispatcher["CONTROLLER"];
	}
	
	function current_method() {
		return $this->dispatcher["METHOD"];
	}
	
	function current_parameters() {
		return $this->dispatcher["PARAMETERS"];
	}
	
	function assign($name,$value){
		$this->template_parser->assign($name,$value);
	}
	
	function display($template,$gui=true){
		$this->assign("SESSION", $this->session_get());
		if(!$this->template_parser->template_exists($template)) {
			$template = "errors/404.template.html";
		}
		
		if(!isset($this->description)) {
			$this->description = $this->template_parser->get_config_vars("_description_".strtolower($this->dispatcher["CONTROLLER"]));
			if(!isset($this->description)) {
				$this->description = $this->template_parser->get_config_vars("_description");
			}
		}
		
		$DOC = array(
			"language" => $this->session_get("language"),
			"languages" => $this->languages,
			"languages_long" => $this->languages_long,
			"title_delimiter" => $this->title_delimiter,
			"title" => isset($this->title) ? $this->title : $this->template_parser->get_config_vars(strtolower($this->dispatcher["CONTROLLER"])),
			"description" => $this->description
		);
		$this->assign("DOCUMENT",$DOC);
		
		$html = $this->parse($template);
		if ($gui){
			$this->assign("__content",$html);
			$html = $this->parse($this->secure?"admin.html":"index.html");
		}
		echo $html;
	}
	
	function parse($template){
		$return = $this->template_parser->fetch($template);
		return $return;
	}
	
	private function _isUserLoggedIn() {
		$userid = $this->getUserId();
		return $userid>0 ? true : false;
	}
	
	public function login() {
		$username = getFromInput("username");
		$password = getFromInput("password");
		
		$userid = $this->Admin->findOne("id",array(
			"username"	=> $username,
			"password"	=> $password
		));
		
		$this->session_set("login_message","Login failed");
		if ($userid) {
			$sessid = session_id();
			setcookie("user",$sessid,0,strlen(ROOT)>0 ? ROOT : "/");
			$q = "UPDATE users SET session='$sessid', last_login=NOW() WHERE id=$userid";
			
			$this->Admin->_alter($q);
			$this->session_set("login_message","");
		}
		redirect("/admin");
	}
	
	public function getUserId() {
		$sessid = $_COOKIE["user"];
		if($sessid) {
			return $this->Admin->findOne("id",array(
				"session"	=> $sessid
			));
		}
		return false;
	}
	
	public function session_get($name=null) {
		return $name?$_SESSION[$this->name][$name]:$_SESSION[$this->name];
	}
	
	public function session_set($name,$value="") {
		$_SESSION[$this->name][$name] = $value;
	}
	
	public function logout() {
		$userid = $this->getUserId();
		setcookie("user","",0,strlen(ROOT)>0 ? ROOT : "/");
		$this->Admin->_alter("UPDATE users SET session='' WHERE id=$userid LIMIT 1");
		redirect("/admin");
	}
	
	public function translate(&$data, $entity) {
		$lang = $this->session_get("language");
		if($lang != "sr") {
			foreach ($data as &$row) {
				$this->translateRow($row, $entity);
			}
		}
	}
	public function translateRow(&$row, $entity) {
		$lang = $this->session_get("language");
		if($lang != "sr") {
			foreach ($row as $field=>&$value) {
				$translation = $this->Translate->findOne("translate",array("entity"=>$entity, "entity_id"=>$row["id"], "entity_field"=>$field, "lang"=>$lang));
				if($translation) {
					$value = $translation;
				}
			}
		}
	}
	
}

?>